from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from .models import Menu
from frame_server.serializers import BaseSerializer as BSerializer

class AddEditValidateBase(BSerializer):
    parentId = serializers.IntegerField(required=False, allow_null=True)
    code = serializers.CharField(max_length=100)
    name = serializers.CharField(max_length=100)
    alias = serializers.CharField(max_length=100)
    source = serializers.CharField(max_length=255)
    sort = serializers.IntegerField()
    category = serializers.IntegerField()
    action = serializers.IntegerField(required=False, allow_null=True)
    
    def to_internal_value(self, data):
        for k in data.keys():
            data[k] = None if data[k]=='' else data[k]
        return super().to_internal_value(data)
    
    def validate_parentId(self, val):
        if val:
            objs = Menu.objects.filter(id=int(val))
            if not objs.exists():
                raise serializers.ValidationError("上级菜单不存在")
            return objs.only('pk').first()
        return None
    
    class Meta:
        model = Menu
        validators = [
            # 联合唯一验证
            UniqueTogetherValidator(Menu.objects.only('code', 'name').all(), ['code','name'], message='菜单编码和名称不能重复')
        ]

class AddValidate(AddEditValidateBase):

    def validate(self, data):
        if data.get('path')==None and data['category'] == 1:
            raise serializers.ValidationError("路由地址不能为空")
        return data
    
    class Meta(AddEditValidateBase.Meta):
        exclude = ['id']
    
class EditValidate(AddEditValidateBase):
    id = serializers.IntegerField(error_messages={"required":'id不能为空'})
    
    def validate_id(self, val):
        if not Menu.objects.filter(id=val).exists():
            raise serializers.ValidationError("编辑对象不存在")
        return val
    
    class Meta(AddEditValidateBase.Meta):
        fields = '__all__'
